package com.soboot.response;

import cn.hutool.http.HttpStatus;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @Author:
 * @createTime: 2022年09月19日 22:01:30
 * @version:
 * @Description:
 * @Copyright:
 */
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Result<T> {

    private static final long serialVersionUID = 1L;

    private boolean success;
    private int code;
    private String msg;
    private T data;
    private long timestamp;

    public static Result fail() {
        return fail(null);
    }

    public static Result fail(String message) {
        return fail(null, message);
    }

    public static Result fail(Integer code, String message) {
        if(code == null) {
            code = HttpStatus.HTTP_INTERNAL_ERROR;
        }
        if(message == null) {
            message = "服务器内部错误";
        }
        return build(code, false, message);
    }

    public static Result success() {
        return success(null);
    }

    public static Result success(String message) {
        return success(null, message);
    }

    public static Result success(Integer code, String message) {
        if(code == null) {
            code = HttpStatus.HTTP_OK;
        }
        if(message == null) {
            message = "操作成功";
        }
        return build(code, true, message);
    }

    public static <T> Result<T> success(T data){
        Result<T> wrapper = success();
        wrapper.setData(data);
        return wrapper;
    }

    private static Result build(int code, boolean success, String message) {
        return Result.builder()
                .code(code)
                .success(success)
                .msg(message)
                .timestamp(System.currentTimeMillis())
                .build();
    }
}
